package com.atguigu.gmall.scheduled.jobHandler;

import com.atguigu.gmall.scheduled.mapper.CartMapper;
import com.atguigu.gmall.scheduled.pojo.Cart;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class CartJobHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CartMapper cartMapper;
    private static final String EXCEPTION_KEY = "cart:exception";
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final String KEY_PREFIX = "cart:info:";
    @XxlJob("cartSyncDataJobHandler")
    public ReturnT<String> syncData(String param){
        //读取redis中异常的数据
        BoundSetOperations<String, String> setOps = redisTemplate.boundSetOps(EXCEPTION_KEY);

        //遍历异常用户的id
        String userId = setOps.pop();//pop方法作用是获取并删除其中的一个元素
        while (StringUtils.isNotBlank(userId)){
            //清空当前userId用户mysql中的购物车
            cartMapper.delete(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId,userId));
            //读取redis中该用户的购物车
            BoundHashOperations<String, Object, Object> boundHashOps =
                    redisTemplate.boundHashOps(KEY_PREFIX + userId);
            //获取cart的json
            List<Object> cartJson = boundHashOps.values();
            if (CollectionUtils.isEmpty(cartJson)){
                //同步下一个用户的购物车
                userId = setOps.pop();
                continue;
            }
            //遍历购物车json数据
            cartJson.forEach(json->{
                try {
                    //反序列化成cart对象
                    Cart cart = objectMapper.readValue(json.toString(), Cart.class);
                    //新增到MySQL数据库
                    cartMapper.insert(cart);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

            });
            //获取下一个userId
            userId = setOps.pop();
        }
        return ReturnT.SUCCESS;
    }
}
